package study.wechat.applet.client.session;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import study.wechat.applet.client.WechatHttp;

import java.util.Map;

/**
 * 小程序登录
 * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
 */
@Slf4j
@Component
public class SessionClient {

    private static final String PATH = "/sns/jscode2session";

    @Value("${wechat.applet.appId}")
    private String appId;
    @Value("${wechat.applet.appSecret}")
    private String appSecret;

    public SessionInfo getSessionInfo(String jsCode) {
        //
        Map<String, Object> param = Maps.newHashMap();
        param.put("appid", appId);
        param.put("secret", appSecret);
        param.put("grant_type", "authorization_code");
        param.put("js_code", jsCode);
        //
        String body = WechatHttp.get(PATH, param);
        SessionInfo info = JSONUtil.toBean(body, SessionInfo.class);
        return info;
    }
}
